package fy.uap.dao;

import fy.config.FyConfig;
import fy.uap.bean.FundsBean;
import fy.util.DBUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FundsDao
{
  private static Log log = LogFactory.getLog(FundsDao.class);
  private FundsBean fundsBean;
  private String uappk_corp = null;
  private String P_dept = null;
  private String P_type = null;
  private String Abs = null;
  private String AbsValue = null;
  private static final String insertSQL = "insert into FYFUND_OA_BILLCOST_TEMP (PK_ID,BILL_NO,PK_CORP,PK_COSTSUBJ,CURR_CODE,BILL_DATE,BILL_AMOUNT,ADV_AMOUNT,OPP_CORP,OPP_ACC_NAME,OPP_ACC_NO,OPP_ACC_BANK,OPP_ACC_BANK_TYPE,ABS,MEMO,VOUCHER_COUNT,OPERATOR,OPERATOR_DATE,BILL_STATUS) select ?,?,?,(select nvl(pk_costsubj,'') from dual left join (select a.pk_costsubj from v_fyfund_costsubj_for_oa a where a.costname = ? and rownum = 1) on 1 = 1),?,?,?,?,?,?,?,?,?,?,?,?,?,?,? from dual where not exists(select * from FYFUND_OA_BILLCOST_TEMP t where t.bill_no = ?)";
  private static final String insertCostSQL = "insert into OA_Cost_To_UAP (P_ID,P_CORP,P_DEPT,P_TYPE,P_COST,TS,NOTE)values ( ?, ?, ?, ?, ?, ?, ?)";
  private static final String LOOKUP_XIALA_XINGJI = "SELECT c.SHOWVALUE FROM  CTP_ENUM_ITEM  c WHERE c.ENUMVALUE=? AND c.REF_ENUMID=?";
  
  public void setFundsBean(FundsBean fundsBean)
  {
    this.fundsBean = fundsBean;
  }
  
  public boolean save()
  {
    Connection conn = null;
    PreparedStatement pst = null;
    
    boolean success = false;
    try
    {
      log.info("Operator:" + this.fundsBean.getOperator());
      if (this.fundsBean.getBill_no().indexOf("B") != -1) {
        this.Abs = (this.fundsBean.getName() + "报销" +this.fundsBean.getProCode() +this.fundsBean.getAbs());
      } else if (this.fundsBean.getBill_no().indexOf("C") != -1) {
        this.Abs = (this.fundsBean.getName() + "报销差旅费" +this.fundsBean.getProCode()+"-" + this.fundsBean.getReasons());
      } else {
        this.Abs = this.fundsBean.getAbs();
      }
      if (this.Abs.length() > 50) {
        this.AbsValue = this.Abs.substring(0, 49);
      } else {
        this.AbsValue = this.Abs;
      }
      /* else if(this.fundsBean.getPk_corp().equals("1025") ){
	  if ((this.fundsBean.getBill_no().indexOf("FM") != -1) || (this.fundsBean.getBill_no().indexOf("CC") != -1)) {
		  this.uappk_corp = "1002";
	  }else {
		  this.uappk_corp = "1025";
	  }
	  
  }*/
      log.info("Abs:" + this.Abs + "AbsValue:" + this.AbsValue);
      if ((this.fundsBean.getPk_corp().equals("1044")) || (this.fundsBean.getPk_corp().equals("1003")) || 
        (this.fundsBean.getPk_corp().equals("1016")) || (this.fundsBean.getPk_corp().equals("1043")) ){
        this.uappk_corp = "1002";
      } else{
        this.uappk_corp = this.fundsBean.getPk_corp();
      }
      log.info("~~~~~~~pk_corp:" + this.uappk_corp + "~~fundsBean.getPk_corp():" + this.fundsBean.getPk_corp() + 
        "~~~fundsBean.getPk_costsubj():" + this.fundsBean.getPk_costsubj());
      
      if ((this.fundsBean.getBill_no().indexOf("FM") != -1) || (this.fundsBean.getBill_no().indexOf("CC") != -1)) {
        for (int temp = 0; this.fundsBean.getP_dept_list().size() > temp; temp++)
        {
          CostSave(temp, this.fundsBean.getBill_no());
          log.info("新增部分:" + temp + this.fundsBean.getBill_no());
        }
      }
      
      conn = DBUtil.connect(FyConfig.getUAP_DB_CONFIG());
      log.info("正式Operator:" + this.fundsBean.getOperator());
      
      conn.setAutoCommit(false);
      pst = conn.prepareStatement("insert into FYFUND_OA_BILLCOST_TEMP (PK_ID,BILL_NO,PK_CORP,PK_COSTSUBJ,CURR_CODE,BILL_DATE,BILL_AMOUNT,ADV_AMOUNT,OPP_CORP,OPP_ACC_NAME,OPP_ACC_NO,OPP_ACC_BANK,OPP_ACC_BANK_TYPE,ABS,MEMO,VOUCHER_COUNT,OPERATOR,OPERATOR_DATE,BILL_STATUS) select ?,?,?,(select nvl(pk_costsubj,'') from dual left join (select a.pk_costsubj from v_fyfund_costsubj_for_oa a where a.costname = ? and rownum = 1) on 1 = 1),?,?,?,?,?,?,?,?,?,?,?,?,?,?,? from dual where not exists(select * from FYFUND_OA_BILLCOST_TEMP t where t.bill_no = ?)");
      pst.setString(1, this.fundsBean.getPk_id());
      pst.setString(2, this.fundsBean.getBill_no());
      pst.setString(3, this.uappk_corp);
      if (this.fundsBean.getPk_costsubj().equals("专利费用")||this.fundsBean.getPk_costsubj().equals("邮电费")) {
        pst.setString(4, "其他管理销售费用");
      } else {
        pst.setString(4, this.fundsBean.getPk_costsubj());
      }
      pst.setString(5, this.fundsBean.getCurr_code());
      pst.setString(6, this.fundsBean.getBill_date());
      pst.setString(7, this.fundsBean.getBill_amount());
      pst.setString(8, this.fundsBean.getAdv_amount());
      pst.setString(9, this.fundsBean.getOpp_corp());
      pst.setString(10, this.fundsBean.getOpp_acc_name());
      pst.setString(11, this.fundsBean.getOpp_acc_no());
      pst.setString(12, this.fundsBean.getOpp_acc_bank());
      pst.setString(13, this.fundsBean.getOpp_acc_bank_type());
      
      pst.setString(14, this.AbsValue);
      pst.setString(15, this.fundsBean.getMemo());
      pst.setString(16, this.fundsBean.getVoucher_count());
      pst.setString(17, this.fundsBean.getOperator());
      pst.setString(18, this.fundsBean.getOperator_date());
      pst.setString(19, "1");
      pst.setString(20, this.fundsBean.getBill_no());
      pst.execute();
      conn.commit();
      success = true;
    }
    catch (Exception e)
    {
      DBUtil.rollback(conn);
      e.printStackTrace();
      log.error("资金系统写入数据异常，异常单据号为:" + this.fundsBean.getBill_no(), e);
    }
    finally
    {
      DBUtil.setAutoCommit(conn, true);
      DBUtil.close(pst, conn);
    }
    return success;
  }
  
  public static Connection connect(String driverClassName, String url, String userName, String password)
    throws Exception
  {
    Class.forName(driverClassName);
    DriverManager.setLoginTimeout(60);
    return DriverManager.getConnection(url, userName, password);
  }
  
  public String getUnitCode(String code, String temp)
  {
	  log.info("code:"+code+"temp:"+temp);
    Connection conn2 = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    try
    {
      conn2 = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
      pst = conn2.prepareStatement("SELECT c.SHOWVALUE FROM  CTP_ENUM_ITEM  c WHERE c.ENUMVALUE=? AND c.REF_ENUMID=?");
      pst.setString(1, code);
      pst.setString(2, temp);
      rs = pst.executeQuery();
      if (rs.next()) {
        code = rs.getString(1);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      DBUtil.close(rs, pst);
    }
    return code;
  }
  
  public boolean CostSave(int temp, String Bill_no)
  {
    boolean success = false;
    Connection conn1 = null;
    PreparedStatement pst = null;
    try
    {
    	if (uappk_corp.equals("1002")) {
    		log.info("1002");
			if (fundsBean.getP_dept_list().get(temp).equals("")) {
				P_dept = "缺省";
			} else {
				P_dept = getUnitCode(fundsBean.getP_dept_list().get(temp), "-3492353121871183070");
			}
			if (Bill_no.indexOf("B") != -1) {
				// 报销封面费用类型
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "8157573833659796347");
			} else {
				// 差旅费用费用类型
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-6471804149242051035");
			}
    	} else if(uappk_corp.equals("1017")||uappk_corp.equals("1018")||uappk_corp.equals("1019")||uappk_corp.equals("1021")||uappk_corp.equals("1040")) {
			if (fundsBean.getP_dept_list().get(temp).equals("")) {
			P_dept = "缺省";
		} else {
			P_dept = fundsBean.getP_dept_list().get(temp);
		}
			if (Bill_no.indexOf("B") != -1) {
				// 正式值
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-8913705840790517082");
			} else {
				// 正式值
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-9119510787155409117");
			}
		} else {
			if (fundsBean.getP_dept_list().get(temp).equals("")) {
			P_dept = "缺省";
		} else {
			P_dept = fundsBean.getP_dept_list().get(temp);
		}
			if (Bill_no.indexOf("B") != -1) {
				// 测试值
			//	P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-2789316785681579454");
				// 正式值
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-1115023073716646373");
			} else {
				// 测试值
				//P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-7162621463629380870");
				// 正式值
				P_type = getUnitCode(fundsBean.getP_type_list().get(temp), "-9119510787155409117");
			}
		}
      conn1 = DBUtil.connect(FyConfig.getUAP_DB_CONFIG());
      Date now = new Date();
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String costDate = dateFormat.format(now);
      conn1.setAutoCommit(false);
      pst = conn1.prepareStatement("insert into OA_Cost_To_UAP (P_ID,P_CORP,P_DEPT,P_TYPE,P_COST,TS,NOTE)values ( ?, ?, ?, ?, ?, ?, ?)");
      pst.setString(1, this.fundsBean.getBill_no());
      pst.setString(2, this.uappk_corp);
   /*   if (((String)this.fundsBean.getP_dept_list().get(temp)).equals("")) {
        this.P_dept = "缺省";
      } else {
        this.P_dept = getUnitCode((String)this.fundsBean.getP_dept_list().get(temp), "-3492353121871183070");
      }*/
      pst.setString(3, this.P_dept);
  /*    if (Bill_no.indexOf("B") != -1) {
        this.P_type = getUnitCode((String)this.fundsBean.getP_type_list().get(temp), "8157573833659796347");
      } else {
        this.P_type = getUnitCode((String)this.fundsBean.getP_type_list().get(temp), "-6471804149242051035");
      }*/
      pst.setString(4, this.P_type);
      log.info("部门：" + this.P_dept + "类型：" + this.P_type + "费用：" + (String)this.fundsBean.getP_cost_list().get(temp));
      pst.setString(5, (String)this.fundsBean.getP_cost_list().get(temp));
      pst.setString(6, costDate);
      pst.setString(7, this.AbsValue);
      pst.execute();
      conn1.commit();
      success = true;
    }
    catch (Exception e)
    {
      DBUtil.rollback(conn1);
      e.printStackTrace();
      log.error("费用明细写入数据异常，异常单据号为:" + this.fundsBean.getBill_no(), e);
    }
    finally
    {
      DBUtil.setAutoCommit(conn1, true);
      DBUtil.close(pst, conn1);
    }
    return success;
  }
}
